package com.scan.bus.presenter;


import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;

import com.baidu.location.BDAbstractLocationListener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scan.bus.BuildConfig;
import com.scan.bus.bean.BaseEntity;
import com.scan.bus.bean.EmptyEntity;
import com.scan.bus.service.ApiService;
import com.scan.bus.service.InterentTools;
import com.scan.bus.util.Common;
import com.scan.bus.util.Constant;
import com.scan.bus.util.HttpDialog;
import com.scan.bus.util.LogUtil;
import com.scan.bus.util.Md5Util;
import com.scan.bus.util.SharedPrefUtil;
import com.scan.bus.view.BaseContract;
import com.scan.bus.view.IView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by zhang on 2017/4/22 16 : 32.
 */

public abstract class BasePresenter<IV extends IView> extends BDAbstractLocationListener implements BaseContract {
    protected static int requestCount;//请求次数
    private final Resources resources;
    private final boolean isOpenLog = BuildConfig.DEBUG;//是否打开log日志 默认打开
    protected Context context;
    protected IV iView;
    protected ObjectMapper objectMapper;
    protected boolean isLoading = false;//是否正在加载
    public int currentPage = 1;//当前页
    protected boolean pageIsLoading = false;//分页是否在加载
    protected String page_size = "20";//分页是否在加载
    protected int allPage;//总页数
    private List<HttpDialog> mDialogList;
    private boolean isDeal=false;

    public BasePresenter(Context context, IV iView) {
        this.context = context;
        this.iView = iView;
        objectMapper = new ObjectMapper();
        requestCount = 0;
        resources = context.getResources();
        mDialogList = new ArrayList<>();
    }

    /**
     * 处理网络请求
     */
    protected abstract void initApi();

    private Retrofit getRetrofit() {
        InterentTools tools = InterentTools.getTools()
                .connectTimeout()
                .addHeaderInterceptor()
                .setLogLevel(isOpenLog, HttpLoggingInterceptor.Level.BODY);

        return tools.getRetrofit();
    }

    /*
     * 需要保存cookie
     * @return
     */
    private Retrofit getSaveCookieRetrofit() {
        InterentTools tools = InterentTools.getTools()
                .connectTimeout()
                .addHeaderInterceptor()
                .addCookiesInterceptor()
                .addReceivedCookiesInterceptor()
                .setLogLevel(isOpenLog, HttpLoggingInterceptor.Level.BODY);


        return tools.getRetrofit();
    }

    /*
     * 需要携带cookie
     * @return
     */
    private Retrofit getAddCookieRetrofit() {
        return getAddCookieRetrofit(60, TimeUnit.SECONDS);
    }

    private Retrofit getAddCookieRetrofit(long timeout, TimeUnit utils) {
        InterentTools tools = InterentTools.getTools()
                .connectTimeout(timeout, utils)
                .addHeaderInterceptor()
                .addCookiesInterceptor()
                .setLogLevel(isOpenLog, HttpLoggingInterceptor.Level.BODY);

        return tools.getRetrofit();
    }

    /*
     * 上传文件
     * @return
     */
    private synchronized Retrofit getUploadFileRetrofit() {
        InterentTools tools = InterentTools.getTools()
                .connectTimeout()
                .addHeaderInterceptor();

        return tools.getRetrofit();
    }

    protected ApiService getApiService() {
        ApiService apiService = getRetrofit().create(ApiService.class);
        return apiService;
    }

    /**
     * 需要保存cookie调用这个
     *
     * @return
     */
    protected ApiService getSaveCookieApiService() {
        ApiService apiService = getSaveCookieRetrofit().create(ApiService.class);
        return apiService;
    }

    /**
     * 需要携带cookie调这个
     *
     * @return
     */
    protected ApiService getAddCookieApiService() {
        ApiService apiService = getAddCookieRetrofit().create(ApiService.class);
        return apiService;
    }

    /**
     * 需要携带cookie调这个
     * 可以设置超时时间
     *
     * @return
     */
    protected ApiService getAddCookieApiService(long timeout, TimeUnit utils) {
        ApiService apiService = getAddCookieRetrofit(timeout, utils).create(ApiService.class);
        return apiService;
    }

    /**
     * 上传文件
     *
     * @return
     */
    protected ApiService getUploadFileApiService() {
        ApiService apiService = getUploadFileRetrofit().create(ApiService.class);
        return apiService;
    }

    /**
     * 请求网络数据
     *
     * @param tCall
     * @param callback
     * @param <T>
     */
    protected <T> void getNetData(final Call<BaseEntity<T>> tCall, final INetDataCallback callback) {
        getNetData(true, false, tCall, callback);
    }

    /**
     * 请求网络数据
     *
     * @param tCall
     * @param callback
     * @param <T>
     */
    protected <T> void getNetData(boolean isLoading, final Call<BaseEntity<T>> tCall, final INetDataCallback<T> callback) {
        getNetData(true, isLoading, tCall, callback);
    }

    /**
     * 请求网络数据
     *
     * @param tCall
     * @param callback
     * @param <T>
     */
    protected <T> void getNetData(final boolean isShowErrorMsg, final boolean isLoading,
                                  final Call<BaseEntity<T>> tCall,
                                  final INetDataCallback<T> callback) {
        if (tCall == null || callback == null)
            return;
        if (isLoading) {
            showDialog();
        }
        tCall.enqueue(new Callback<BaseEntity<T>>() {
            @Override
            public void onResponse(Call<BaseEntity<T>> call, Response<BaseEntity<T>> response) {
                dismissDialog(isLoading);
                if (context instanceof Activity) {
                    if (((Activity) context).isFinishing()) return;
                }
                BaseEntity<T> body = response.body();
                if (body == null) {
                    callback.onFailure();
                    return;
                }
                if (body.status == 200) {//请求成功
                    callback.onSuccess(body);
                } else {
                    callback.onError(body.status, body.msg, body.data,body);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<T>> call, Throwable t) {
                if (t != null)
                    t.printStackTrace();
                dismissDialog(isLoading);
                if (context instanceof Activity) {
                    if (((Activity) context).isFinishing()) return;
                }
                callback.onFailure();
            }
        });
    }

    /**
     * loading隐藏
     */
    public void dialogLoadingDissmiss(){
        dismissDialog(true);
    }


    private void showDialog() {
        HttpDialog httpDialog = new HttpDialog(context);
        if (mDialogList != null) {
            mDialogList.add(httpDialog);
            httpDialog.show();
        }
    }

    private void dismissDialog(boolean isLoading) {
        if (isLoading&&!isEmpty(mDialogList)) {
            mDialogList.get(0).dismiss();
            mDialogList.remove(0);
        }
    }

    private void handlerCode(Integer code, String message, boolean isShowErrorMsg) {
        Common.staticToast(message);
    }

    /**
     * 处理刷新逻辑
     */
    public void onRefresh() {

    }

    /**
     * 设置请求接口参数
     *
     * @param params
     * @return
     */
    protected Map<String, Object> setParams(String... params) {
        Map<String, Object> map = new HashMap<>();
        if (params != null && params.length % 2 == 0) {
            for (int i = 0; i < params.length; i += 2) {
                if (!isEmpty(params[i + 1]))
                    map.put(params[i], params[i + 1]);
            }
        }
        sortAndMD5(map);
        return map;
    }


    public void sortAndMD5(Map<String, Object> map) {
        List<String> strs = new ArrayList<>();
        map.put("device_id", SharedPrefUtil.getCacheSharedPrf("X-Device-ID", ""));
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            strs.add(next);
        }
        Collections.sort(strs);
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < strs.size(); i++) {
            String key = strs.get(i);
            Object value = map.get(key);
            if (value == null) {
                value = "";
            }
            sign.append(key + "=" + value);
            sign.append("&");
            if (i == strs.size() - 1) {
                sign.append("key=" + Constant.KEY);
            }
        }
        map.put("sign", Md5Util.getMD5(sign.toString()).toUpperCase(Locale.ROOT));
    }
    public void sortTestAndMD5(Map<String, Object> map) {
        List<String> strs = new ArrayList<>();
        map.put("device_id", "868035047718143");
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            strs.add(next);
        }
        Collections.sort(strs);
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < strs.size(); i++) {
            String key = strs.get(i);
            Object value = map.get(key);
            if (value == null) {
                value = "";
            }
            sign.append(key + "=" + value);
            sign.append("&");
            if (i == strs.size() - 1) {
                sign.append("key=" + Constant.KEY);
            }
        }
        map.put("sign", Md5Util.getMD5(sign.toString()).toUpperCase(Locale.ROOT));
    }
    /**
     * 将键值对格式成 RequestBody对象并返回
     *
     * @param map
     * @return
     */
    public RequestBody getRequestBody(Map map) {
        String stringEntry = null;
        try {
            if (objectMapper == null) {
                objectMapper = new ObjectMapper();
            }
            stringEntry = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), stringEntry);
        return requestBody;
    }

    /**
     * 判断集合内容是否为空
     *
     * @param list
     * @return
     */
    protected boolean isEmpty(List list) {
        if (list == null) {
            return true;
        }

        if (list.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    protected boolean isEmpty(CharSequence sequence) {
        return TextUtils.isEmpty(sequence);
    }


    /**
     * 上传图片
     * @param filePath
     * @param uploadPath
     */
//    public void uploadPic(List<ImageEntity> filePath, final String uploadPath) {
//        if (isEmpty(filePath)) {
//            return;
//        }
//        List<MultipartBody.Part> parts = new ArrayList<>();
//        for (int i = 0; i < filePath.size(); i++) {
//            File file = filePath.get(i).file;
//            if (file == null || file.length() <= 0)continue;
//            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
//            MultipartBody.Part part = null;
//            try {
//                part = MultipartBody.Part.createFormData("file[]",  URLEncoder.encode(file.getName(),"utf-8"), requestBody);
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//            parts.add(part);
//        }
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("path_name", uploadPath);
//        sortAndMD5(map);
//
//        Call<BaseEntity<UploadPicEntity>> call = getAddCookieApiService().uploadPic(parts,map);
//        getNetData(true, call, new SimpleNetDataCallback<UploadPicEntity>() {
//            @Override
//            public void onSuccess(BaseEntity<UploadPicEntity> entity) {
//                super.onSuccess(entity);
//                UploadPicEntity uploadPicEntity = entity.data;
//                if (uploadPicEntity != null) {
//                    iView.uploadImg(uploadPicEntity);
//                }
//            }
//        });
//    }



}
